مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

مدرسه زبان برنامه‌نویسی PYTHON

وبلاگی جهت معرفی - آموزش و تحلیل زبان برنامه نویسی ‍پایتون

طبقه بندی موضوعی
بایگانی

۱۸ مطلب با کلمه‌ی کلیدی «مثال از پایتون» ثبت شده است

برنامه زیر ضرائب معادله درجه 2 را گرفته و معادله را حل نموده و جوابهای معادله را در صورت حقیقی بودن نمایش می‌دهد. سعی کنید برنامه‌ای بنویسید که جوابهای موهمومی معادله را نیز محاسبه و چاپ کند.


#Programmer : Saeed Damghanian

#Web : Pyschool.blg.ir


import math

a=int(input("Please Enter a: "))

b=int(input("Please Enter b: "))

c=int(input("Please Enter c: "))

delta=b*b-4*a*c

if delta==0 :

    x=(-b + math.sqrt(delta))

    print("Moadele Yek javab darad. X=",x)

elif delta<0:

    print("Moadele javabe haghighi nadarad!")

else :    

    x1=(-b + math.sqrt(delta))/(2*a)

    x2=(-b - math.sqrt(delta))/(2*a)

    print("Moadele 2 javab darad.\n X1= ",x1, "\nX2= " , x2)


#------------Telegram: @Ghoghnous_Iran-----------------------


 

h909262_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۳۰ تیر ۹۸ ، ۰۶:۰۵
سعید دامغانیان

در این پست آموزشی قصد دارم که ارسال ُ نوشتن و ویرایش یک پست الکترونیک را با هم ببینیم و همچنین بعد با پروتکلها و استاندارهایی همچون MIME  و ارسال نامه به این سبک را آموزش دهم. با من (سعید دامغانیان) همراه باشید...

در قطعه کد زیر اولاْ ارسال یک ایمیل ساده را بررسی کنید :

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

حال با استاندارد RFC822 آشنا شده و سپس کد زیر را بررسی کنید :

# Import the email modules we'll need
from email.parser import BytesParser, Parser
from email.policy import default

# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
#     headers = BytesParser(policy=default).parse(fp)

#  Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
        'From: Foo Bar <user@example.com>\n'
        'To: <someone_else@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Now the header items can be accessed as a dictionary:
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))

# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

حال نوبت رسیده کمی فراتر رفته و به استاندارد MIME بپردازیم. نوبت شماست ...

# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

در قطعه کد زیر فصد داریم محتویات یک دایرکتوری را به استاندارد MIME ارسال کنیم...

#!/usr/bin/env python3

"""Send the contents of a directory as a MIME message."""

import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP


def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)


if __name__ == '__main__':
    main()
در اینجا طریقه باز کردن ایمیل دریافتی مشابه بالا را در همان استاندارد بررسی خواهیم نمود 
#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import email
import mimetypes

from email.policy import default

from argparse import ArgumentParser


def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile, 'rb') as fp:
        msg = email.message_from_binary_file(fp, policy=default)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))


if __name__ == '__main__':
    main()

در اینجا یک مثال که نحوه ایجاد یک پیام HTML با یک نسخه متنی ساده است را نوشته ایم. برای ایجاد چیزهای کمی جالب تر، ما یک تصویر مربوط به آن را در بخش HTML می نویسیم و یک کپی از آنچه که ما می خواهیم برای ارسال به دیسک داریم، و همچنین ارسال آن را ذخیره کرده ایم...

#!/usr/bin/env python3

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Salut!</p>
    <p>Cela ressemble à un excellent
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
            recipie
        </a> déjeuner.
    </p>
    <img src="cid:{asparagus_cid}" />
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

اگر پیام از آخرین نمونه ای که نوشتم ارسال شد، در اینجا یکی از راه هایی است که می توانیم آن را پردازش کنیم:

import os
import sys
import tempfile
import mimetypes
import webbrowser

# Import the email modules we'll need
from email import policy
from email.parser import BytesParser

# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser

# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
    msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])

# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines.  Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))

ans = input("View full message?")
if ans.lower()[0] == 'n':
    sys.exit()

# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = {}
if richest['content-type'].maintype == 'text':
    if richest['content-type'].subtype == 'plain':
        for line in richest.get_content().splitlines():
            print(line)
        sys.exit()
    elif richest['content-type'].subtype == 'html':
        body = richest
    else:
        print("Don't know how to display {}".format(richest.get_content_type()))
        sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
    body = richest.get_body(preferencelist=('html'))
    for part in richest.iter_attachments():
        fn = part.get_filename()
        if fn:
            extension = os.path.splitext(part.get_filename())[1]
        else:
            extension = mimetypes.guess_extension(part.get_content_type())
        with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
            f.write(part.get_content())
            # again strip the <> to go from email form of cid to html form.
            partfiles[part['content-id'][1:-1]] = f.name
else:
    print("Don't know how to display {}".format(richest.get_content_type()))
    sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    # The magic_html_parser has to rewrite the href="cid:...." attributes to
    # point to the filenames in partfiles.  It also has to do a safety-sanitize
    # of the html.  It could be written using html.parser.
    f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
    os.remove(fn)

# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.

خروجی قطعه کد بالا را در ذیل ببینید :

To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
From: Pepé Le Pew <pepe@example.com>
Subject: Ayons asperges pour le déjeuner

Salut!

Cela ressemble à un excellent recipie[1] déjeuner.
۰ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۳:۳۲
سعید دامغانیان

  turtle و math  کدی نوشتم که شکل یک لانه ی زنبور را ترسیم کند. با استفاده از


# Hive

# By: Saeed Damghanian


from turtle import *

from math import *


def line(x, y, x2, y2):

    ''' Draw a line from (x, y) to (x2, y2) '''

    penup()

    goto(x, y)

    pendown()

    goto(x2, y2)



def draw_tree(x, y, size, angle,n):

    ''' Draw a tree of given size and angle at (x, y) '''

    if n==1:

        return

    if size < 4:

        return

    x2 = x + size * cos(radians(angle))

    y2 = y + size * sin(radians(angle))

    line(x, y, x2, y2)

    draw_tree(x2, y2, size , angle + 60,n-1)

    draw_tree(x2, y2, size , angle - 60,n-1)



# main program

#tracer(0,0)


#speed(10)

#delay(2)

draw_tree(0, 0, 50, 90,10)

mainloop()


u544287_Untitled.png

۲ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۱:۰۷
سعید دامغانیان

کدی که در ذیل مشاهده می‌کنید یک خورشید را به صورت خطهای هندسی رسم کرده و رنگ میزند. #جالبناک


from turtle import *

color('blue', 'yellow')

begin_fill()

while True:

    forward(200)

    left(100)

    if abs(pos()) < 1:

        break

end_fill()

done()


خروجی کد بالا شکلی مطابق ذیل است. با ما همراه شوید.. . مدرسه پایتون

n488379_Untitled.png

۱ نظر موافقین ۰ مخالفین ۰ ۲۴ تیر ۹۸ ، ۱۰:۵۲
سعید دامغانیان

برنامه ای نوشتم که آدرس یک سایت رو بگیره و آی پی سایت رو نمایش بده. خیلی ساده (البته گرافیکی* #پایتون )


#Code By Saeed Damghanian

#Software Engineer from Semnan


import os, socket

import tkinter as tk

from tkinter import font


def response(a):

    b = socket.gethostbyname(a)

    c = "\n \n \nProgrammer: Saeed Damghanian\nWebsPyschool.blog.ir\nWant to Join our Telegram Channel? >> t.me/ghoghnous_iran"

    return b + c


def do(a):

    label['text'] = response(a)


root = tk.Tk()

root.title('Get Website Ip')


canvas = tk.Canvas(root, height=500, width=600)

canvas.pack()


#background_image1 = tk.PhotoImage(file='bg.png')

#background_label =tk.Label(root, image=background_image1)

#background_label.place(relwidth=1, relheight=1)


frame = tk.Frame(root, bg='#C02F11', bd=5)

frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')


entry = tk.Entry(frame, font=('Modern', 15))

entry.insert(0, 'Website URL')

entry.place(relwidth=0.65, relheight=1)


button = tk.Button(frame, text='Get IP', bd=0, bg='white', fg='#098f00', font=60, command=lambda:do(entry.get()))

button.place(relx=0.7, relheight=1, relwidth=0.3)


lower_frame = tk.Frame(root, bg='#0ed400', bd=10)

lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')


label = tk.Label(lower_frame, font=('Modern', 15), anchor='nw', bg='#323142', fg='white', justify='left', bd=4)

label.place(relwidth=1, relheight=1)


root.mainloop()


g241362_Untitled.png


۰ نظر موافقین ۰ مخالفین ۰ ۲۳ تیر ۹۸ ، ۰۰:۰۰
سعید دامغانیان

مثال هایی از SORT (مرتب سازی ) در پایتون. تحلیل و تفسیر با شما...


a29009_01.jpg

e2519_02.jpg

a944746_03.jpg

o38084_04.jpg


r04659_05.jpg


موفق و پیروز باشید #سعیددامغانیان


۰ نظر موافقین ۰ مخالفین ۰ ۱۲ تیر ۹۸ ، ۱۱:۵۵
سعید دامغانیان

lambda

توابع lambda

ایجاد یک تابع به طور معمول با استفاده از def صورت می گیرد و به طور خودکار آن را به یک متغیر اختصاص می دهد.
این کار نسبت به ساخت دیگر object ها متفاوت است – مانند رشته ها و اعداد صحیح – که می توانند در هنگام کد نویسی و در هر جایی ایجاد شوند بدون اینکه آنها را به یک متغیر اختصاص دهید.
همان کار با توابعی امکان پذیر است، در صورتی که با استفاده از lambda ایجاد می شوند. توابع ایجاد شده در این روش ناشناس هستند.
این رویکرد اغلب هنگام انتقال یک تابع ساده به عنوان یک استدلال به عملکرد دیگر استفاده می شود. نحوه عملکرد آن در مثال زیر نشان داده شده است و شامل کلید واژه lambda است که به دنبال آن یک لیست از استدلال، کولون و بیانات برای ارزیابی و بازگشت پاسخ در نظر گرفته شده است.

def my_func(f, arg):
  return f(arg)

my_func(lambda x: 2*x*x, 5)

نکته: تابع lambda نام خود را از محاسبات لامبدا دریافت می کنند که یک مدل محاسباتی است که توسط کلیسای آلونزو اختراع شده است.

توابع لامبدا مانند توابع معمولی، قدرتمند نیستند.
آنها تنها می توانند کارهایی را انجام دهند که نیاز به یک عمل واحد دارند – معمولا معادل یک خط کد است.
مثال:

#named function
def polynomial(x):
    return x**2 + 5*x + 4
print(polynomial(-4))

#lambda
print((lambda x: x**2 + 5*x + 4) (-4))

خروجی:

>>>
0
0
>>>

نکته: در کد بالا، ما یک تابع ناشناس ایجاد کردیم و با یک استدلال آن را نامگذاری کردیم.

توابع lambda را می توان به متغیرها اختصاص داد و از توابع عادی استفاده کرد.
مثال:

double = lambda x: x * 2
print(double(7))

خروجی:

>>>
14
>>>

نکته:با این حال، به ندرت دلیل خوبی برای انجام این کار وجود دارد – معمولا بهتر است یک تابع با def تعریف کنیم.

۰ نظر موافقین ۰ مخالفین ۰ ۱۲ تیر ۹۸ ، ۱۱:۴۳
سعید دامغانیان

برنامه نویسی تابع گرا یا functional programming

برنامه نویسی تابع گرا یک سبک برنامه نویسی است که بر اساس توابع است.
بخش کلیدی برنامه نویسی تابع گرا در پایتون، توابع مرتبه بالاتر است. ما این ایده را به طور خلاصه در درس قبلی در مورد توابع به عنوان اشیا دیده ایم. توابع مرتبه بالاتر، توابع دیگر را به عنوان آرگومان دریافت می کنند، و یا آنها را به عنوان نتایج به ارمغان می آورند.
مثال:

def apply_twice(func, arg):
   return func(func(arg))

def add_five(x):
   return x + 5

print(apply_twice(add_five, 10))

خروجی:

>>>
20
>>>

نکته:تابع apply_twice عمل دیگری را به عنوان استدلال آن انجام می دهد و آن را دو بار در داخل بدنه کد خود فرا خوانی می کند.

توابع خالص و ناخالص (pure and impure functions)

برنامه نویسی کاربردی به دنبال استفاده از توابع خالص است. توابع خالص عوارض جانبی ندارند و مقداری را که فقط به استدلال آنها بستگی دارد، بازمی گرداند.
این کار در ریاضی به این صورت عمل می کند: به عنوان مثال، cos (x)، برای همان مقدار x، همیشه همان نتیجه را به دست می آورد.
در زیر نمونه هایی از توابع خالص و ناخالص هستند.
عملکرد خالص:

def pure_function(x, y):
  temp = x + 2*y
  return temp / (2*x + y)

عملکرد ناخالص:

some_list = []

def impure(arg):
  some_list.append(arg)

نکته:تابع بالا خالص نیست، زیرا حالت some_list را تغییر داد.

استفاده از توابع خالص هم مزایا و هم معایب دارد.
توابع خالص عبارتند از:
– ساده تر در شفاف سازی و تست کردن
– کارآمدتر. هنگامی که عملکرد برای یک ورودی ارزیابی می شود، نتیجه می تواند ذخیره شود و به دفعه بعد که عملکرد آن ورودی مورد نیاز است، نسبت دهد تا تعداد دفعاتی که تابع فراخوانی می شود کاهش یابد. به این مدل memoization یا به اصطلاح یادداشت برداری می گویند.
– راحت تر به صورت parallel یا موازی اجرا شود.

نکته:معایب اصلی استفاده از تنها توابع خالص این است که آنها وظیفه ساده و آسان I / O را به شدت پیچیده می کنند، زیرا به نظر می رسد به طور ذاتی نیاز به عوارض جانبی دارد. همچنین می توانند در بعضی موقعیت ها دشوار باشند.

۰ نظر موافقین ۰ مخالفین ۰ ۱۲ تیر ۹۸ ، ۱۱:۴۱
سعید دامغانیان

u30753_Untitled-1.jpg

۲ نظر موافقین ۰ مخالفین ۰ ۱۲ تیر ۹۸ ، ۱۱:۲۵
سعید دامغانیان

Tuple در پایتون

Tuple ها به لیستها بسیار شبیه هستند، به جز اینکه Tuple ها غیرقابل تغییر هستند .
همچنین، آنها با استفاده از پرانتز، به جای براکت مربعی، ایجاد می شوند.
مثال:

words = ("spam", "eggs", "sausages",)

شما می توانید با مقادیر خود در مقیاس به همان اندازه که با لیست ها دسترسی داشتید دسترسی پیدا کنید:

print(words[0])

تلاش برای تخصیص یک مقدار در یک Tuple، یک TypeError را ایجاد می کند.

words[1] = "cheese"

خروجی:

>>>
TypeError: 'tuple' object does not support item assignment
>>>

نکته:مانند لیست ها و dictionary ها، tuple ها را می توان در داخل یکدیگر قرار داد.

tuple ها را می توان فقط با جدا کردن مقادیر با کاما و بدون پرانتز ایجاد کرد.
مثال:

my_tuple = "one", "two", "three"
print(my_tuple[0])

خروجی:

>>>
one
>>>

یک tuple خالی با استفاده از یک جفت پرانتز خالی ایجاد می شود.

tpl = ()

نکته:tuple ها سریعتر از لیست ها هستند اما قابل تغییر نیستند.

۰ نظر موافقین ۰ مخالفین ۰ ۰۷ تیر ۹۸ ، ۲۲:۰۱
سعید دامغانیان